﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Pixysoft.Framework.Configurations.Core
{
    class HtmlCell : IHtmlCell
    {
        string parentpath;

        int nestLevel = 0;

        int tableIndex = 0;

        int rowIndex = 0;

        int cellIndex = 0;

        IHtmlNode node;

        public HtmlCell(IHtmlNode node, string parentpath, int nestLevel, int tableIndex, int rowIndex, int cellIndex)
        {
            this.parentpath = parentpath;
            this.nestLevel = nestLevel;
            this.tableIndex = tableIndex;
            this.rowIndex = rowIndex;
            this.cellIndex = cellIndex;
            this.node = node;
        }

        public string ParentPath
        {
            get { return parentpath; }
        }

        public int NestLevel
        {
            get { return nestLevel; }
        }

        public int TableIndex
        {
            get { return tableIndex; }
        }

        public int RowIndex
        {
            get { return rowIndex; }
        }

        public int CellIndex
        {
            get { return cellIndex; }
        }

        public string Content
        {
            get { return node.Serialize(); }
        }

        public IHtmlNode HtmlNode
        {
            get
            {
                return node;
            }
        }

        public IHtmlTableCollection Tables
        {
            get
            {
                return new HtmlTableCollection(node.Nodes,
                    string.Format("{0}{1}.{2}.{3}{4}",
                    parentpath, tableIndex, rowIndex, cellIndex, StringHelper.default_html_pathspliter),
                    nestLevel + 1);
            }
        }

        public string Serialize()
        {
            FormatStringBuilder builder = new FormatStringBuilder();
            for (int i = 0; i < nestLevel * 3; i++)
                builder.Indent();

            builder.Indent();
            builder.Indent();

            builder.AppendLine(string.Format("<cell path='{0}{1}.{2}.{3}' nest='{4}'>",
                parentpath, tableIndex, rowIndex, cellIndex, nestLevel));
            if (Tables.Count > 0)
            {
                builder.Append(Tables.Serialize());
            }
            else
            {
                builder.Indent();
                builder.AppendLine(string.Format("<content>{0}</content>", node.Serialize()));
                builder.Outdent();
            }
            builder.AppendLine("</cell>");
            builder.Outdent();
            builder.Outdent();

            for (int i = 0; i < nestLevel * 3; i++)
                builder.Outdent();

            return builder.ToString();
        }
    }
}
